package au.org.tern.ecoinformatics.oai.provider.util;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;

import eml.ecoinformatics_org.eml_2_1.Eml;

public class JaxbUtil {

	private static JAXBContext jaxbEmlContext;
	static {
		try {
			jaxbEmlContext = JAXBContext.newInstance("eml.ecoinformatics_org.eml_2_1");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String marshallEmlToString(Eml eml) {
		try {
			Marshaller marshaller = jaxbEmlContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
			marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
				@Override
				public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
					if (namespaceUri.equals("eml://ecoinformatics.org/eml-2.1.0")) {
						return "eml";
					}
					return suggestion;
				}
			});
			StringWriter writer = new StringWriter();
			marshaller.marshal(eml, writer);

			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
